package main;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.security.InvalidParameterException;

import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

import mvc.CFormController;
import mvc.constants.EntityEnum;
import mvc.view.IView;
import mvc.view.controls.menu.CMenuItem;
import utils.CDBDebug;
public final class CMDIApp extends JFrame implements ActionListener{

	private JDesktopPane contentPane;
	private JMenuBar menuBar = new JMenuBar();
	private CFormController formController = new CFormController();

	public CMDIApp() {
		setSize(new Dimension(1140, 880));
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 1140, 880);
		setJMenuBar(menuBar);

		JMenu mainMenu = addMenu("Main");
		addMenuItem("Words", mainMenu, null, null, EntityEnum.WORDS);
		addMenuItem("Subs", mainMenu, null, null, EntityEnum.SUBS);
		addMenuItem("Verbs", mainMenu, null, null, EntityEnum.VERBS);

		JMenu debugMenu = addMenu("Debug");
		addMenuItem("SQL Debugger", debugMenu, null, CDBDebug.class, EntityEnum.CUSTOM);


		contentPane = new JDesktopPane();
		setContentPane(contentPane);
	}

	private JMenu addMenu(String caption){
		JMenu newMenu = new JMenu(caption);
		menuBar.add(newMenu);
		return newMenu;
	}

	private void addMenuItem(String pCaption, JMenu pParentMenu, JMenuItem pParentItem, 
			                     Class<? extends IView> pFormClass, EntityEnum pEntityName){
		CMenuItem newItem = new CMenuItem(pCaption, (Class<IView>) pFormClass, pEntityName.name());
		newItem.addActionListener(this);

		if (pParentMenu != null)
			pParentMenu.add(newItem);
		else if (pParentItem != null)
			pParentItem.add(newItem);
		else throw new InvalidParameterException("parentMenu or parentItem cannot be null!");
	}

	@Override
	public void actionPerformed(ActionEvent pEv) {
		CMenuItem menuItem = (CMenuItem) pEv.getSource(); 
		formController.setAppContainer(getContentPane()); 
		formController.createChild(menuItem.getFormClass());
	}
}
